import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class DragonOath_mesh(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(DragonOath_mesh,self).__init__("XAC")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def read_name(self):
        
        name = []
        char = self.inFile.read_char()
        while char != "\x0A":
            name.append(char)
            char = self.inFile.read_char()
        return ''.join(name)
        
    def parse_texture(self):
        
        pass
    
    def parse_mesh(self):
        
        pass
    
    def parse_materials(self):
        
        pass
    
    def parse_vertices(self, meshName, numVerts):
        
        for i in xrange(numVerts):
            vx, vy, vz = self.inFile.read_float(3)
            nx, ny, nz = self.inFile.read_float(3)
            tu, tv = self.inFile.read_float(2)
            print vx, vy, vz
            
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])
    
    def parse_faces(self, meshName, numFaces):
        
        for i in xrange(numFaces):
            coords = self.inFile.read_short(3)
            
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, coords)
        
    def parse_file(self):
        '''Main parser method. Can be replaced'''

        filesize = self.inFile.filesize()
        meshName = "obj"
        self.create_object(meshName)
        
        chunk = self.inFile.read_short()
        header = self.inFile.read_string(23)
        
        while self.inFile.tell() != filesize:
            chunk = self.inFile.read_short()
            chunkLen = self.inFile.read_long()
            
            print hex(chunk), chunkLen
            if chunk == 0x3000:
                self.parse_mesh()
                break

        
        #self.inFile.seek(1, 1)
        
        #numFaces = self.inFile.read_long() / 3
        #self.inFile.seek(1, 1)
        #print("%d faces" %numFaces)
        #self.parse_faces(meshName, numFaces)
        
        #self.inFile.seek(6, 1)
        #numVerts = self.inFile.read_long()
        #self.inFile.seek(70, 1)
        #print("%d vertices" %numVerts)
        #self.parse_vertices(meshName, numVerts)
        
def read_file(path):
    '''Read the file'''
    
    openFile = StructReader(open(path, 'rb'))
    obj = DragonOath_mesh(inFile=openFile)
    obj.parse_file()
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "\x00\x10[MeshSer", "MESH", "Dragon Oath MESH"

if __name__ == '__main__':
    
    file1 = ""
    obj = read_file(file1)